import registerRouter from "@/utils/registerRouter";
import { overviewRoute } from "@/routes/config";
import { LoginRouteComponent } from "./basics.router";
export const permission = (router: any) => {
  router.beforeEach(async (to: any, from: any, next: any) => {
    document.title = !isEmptyType(to.meta.title)
      ? to.meta.title + " - " + "Coin Cupid"
      : "";
    const mainStore = useMainStore();
    const userStore = useUserStore();
    if (to.meta && to.meta.keepAlive) mainStore.addCacheView(to);
    if (!!userStore.token) {
      if (to.name === LoginRouteComponent.name)
        $addTags({
          name: overviewRoute.meta.title,
          path: overviewRoute.path,
          callback: () => next(overviewRoute.path),
        });
      else {
        const routeStore = useRouteStore();
        if (routeStore.routes.length === 0) await routeStore?.fetchMenuList();
        const isRegisterRouter = registerRouter(router, routeStore.routes);
        if (to.name === "404" && !isRegisterRouter)
          next({ path: to.path, query: to.query });
        else next();
      }
    }
    if (!userStore.token)
      if (to.name === LoginRouteComponent.name) next();
      else next(LoginRouteComponent.path);
  });
};
